package com.ldg.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ld.pojo.PayVo;
import com.ld.pojo.TbPayLog;
import com.ld.utils.IdWorker;
import com.ldg.order.entity.Cart;
import com.ldg.order.entity.TbAddress;
import com.ldg.order.entity.TbOrder;
import com.ldg.order.entity.TbOrderItem;
import com.ldg.order.mapper.TbAddressMapper;
import com.ldg.order.mapper.TbOrderItemMapper;
import com.ldg.order.mapper.TbOrderMapper;
import com.ldg.order.mapper.TbPayLogMapper;
import com.ldg.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: Liudao
 * @Date: 2022-10-18-19:48
 * @Description:
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private TbAddressMapper addressMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private TbOrderItemMapper orderItemMapper;
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private TbPayLogMapper payLogMapper;

    @Override
    public List<TbAddress> findAddrByUname(String name) {
        return addressMapper.selectList(new QueryWrapper<TbAddress>().eq("user_id",name));
    }

    @Override
    public List<Cart> findCartByUname(String name) {
        //得到购物车列表字符串，转换为集合后返回

        return JSON.parseArray(redisTemplate.opsForValue().get(name),Cart.class);
    }

    @Override
    @Transactional
    public void add(String name, TbOrder tbOrder) {
        List<String> ids = new ArrayList<>();   //代表所有订单的编号
        double sum = 0;                         //代表所有订单的总金额
        //从redis中得到购物车列表,这里直接调用前面的方法就可以了
        List<Cart> cartList = findCartByUname(name);
        //遍历购物车集合
        for (Cart cart : cartList) {
            TbOrder order = new TbOrder();      //代表要添加的订单
            double total = 0;                   //代表该订单的总金额
            //生成orderid
            long orderId = idWorker.nextId();
            order.setOrderId(orderId);
            ids.add(orderId+"");
            //为订单其他值赋值
            order.setStatus("1");  //状态：1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭,7、待评价
            order.setCreateTime(new Date());
            order.setPaymentType(tbOrder.getPaymentType());
//            order.setPaymentType("1");
            order.setSellerId(cart.getSellerId());
            order.setReceiver(tbOrder.getReceiver());
            order.setReceiverAreaName(tbOrder.getReceiverAreaName());
            order.setReceiverMobile(tbOrder.getReceiverMobile());
            order.setUpdateTime(new Date());
            order.setSourceType("2");  //订单来源：1:app端，2：pc端，3：M端，4：微信端，5：手机qq端
            order.setUserId(name);
            System.out.println(tbOrder.getPaymentType());
            //遍历订单项
            for (TbOrderItem tbOrderItem : cart.getOrderItemList()) {
                //设置订单项关联的订单id
                tbOrderItem.setOrderId(orderId);
                //设置id
                tbOrderItem.setId(idWorker.nextId());
                //计算小计金额
                tbOrderItem.setTotalFee(tbOrderItem.getPrice().multiply(new BigDecimal(tbOrderItem.getNum())));
                //计算总金额
                total += tbOrderItem.getTotalFee().doubleValue();
                //添加订单项
                orderItemMapper.insert(tbOrderItem);
            }
            //计算所有订单的总金额
            sum += total;
            //设置支付金额
            order.setPayment(new BigDecimal(total));
            //添加订单
            orderMapper.insert(order);
        }
        //向支付日志中添加记录
        if (tbOrder.getPaymentType().equals("1")){  //代表支付类型，1是支付宝支付
            TbPayLog payLog = new TbPayLog();
            payLog.setCreateTime(new Date());               // 创建日期
            payLog.setOutTradeNo(idWorker.nextId() + "");   // 支付日志编号
            payLog.setPayType(tbOrder.getPaymentType());
            payLog.setTradeState("0");                      // 支付状态，代表未支付
            payLog.setUserId(name);                         // 登录名
            payLog.setTotalFee((long)(sum));            // 所有订单的总金额，以分为单位
            payLog.setOrderList(ids.toString().replace("[","").replace("]",""));
            payLogMapper.insert(payLog);
            //放到redis中
            redisTemplate.opsForValue().set(name + ":paylog",JSON.toJSONString(payLog));
        }

    }

    @Override
    public TbPayLog findPayLogByUname(String name) {
        return JSON.parseObject(redisTemplate.opsForValue().get(name+":paylog"),TbPayLog.class);
    }


    //******************************************************************
    //6. 从redis中查询Payvo对象
    @Override
    public PayVo findPayVoByname(String name) {
        //6.1 根据登录名得到支付日志对象
        TbPayLog payLog = findPayLogByUname(name);
        //6.2 定义PayVo对象
        PayVo vo = new PayVo();
        vo.setOut_trade_no(payLog.getOutTradeNo());
        vo.setTotal_amount(payLog.getTotalFee() + "");
        vo.setSubject("六道购商城支付订单");
        vo.setBody("一个良好的网上交易平台...");
        return vo;
    }

    @Override
    public TbOrder findOrdersById(String id) {
        return orderMapper.selectById(id);
    }

    @Override
    public void update(TbOrder order) {
        orderMapper.updateById(order);
    }

    //7. 根据登录名得到订单列表
    @Override
    public List<TbOrder> findOrdersByName(String name) {
        //7.1 根据当前登录的用户id查询其订单列表
        List<TbOrder> orderList = orderMapper.selectList(new QueryWrapper<TbOrder>().eq("user_id", name));
        //7.2 遍历订单，并添加某订单关联的订单项列表
        for (TbOrder order : orderList) {
            List<TbOrderItem> orderItems = orderItemMapper.selectList(new QueryWrapper<TbOrderItem>().eq("order_id", order.getOrderId()));
            order.setOrderItems(orderItems);
        }
        return orderList;
    }
}
